package com.raos.example.thread.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步调用线程池配置
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2022/6/16 09:32
 */
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    @Bean(name = "defaultPoolTaskExecutor")
    public ThreadPoolTaskExecutor executor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize(threadPoolConfig.getCoreNum());
        //线程最大数量，线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        taskExecutor.setMaxPoolSize(threadPoolConfig.getMaxNum());
        //缓存队列
        taskExecutor.setQueueCapacity(threadPoolConfig.getQueueSize());
        //超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setKeepAliveSeconds(threadPoolConfig.getAliveSecond());
        //执行异步方法的线程名称
        taskExecutor.setThreadNamePrefix(threadPoolConfig.getNamePrefix());
        /**
         * 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize，如果还有任务到来就会采取任务拒绝策略
         * 通常有以下四种策略：
         *   ThreadPoolExecutor.AbortPolicy: 丢弃任务并抛出RejectedExecutionException异常。
         *   ThreadPoolExecutor.DiscardPolicy: 也是丢弃任务，但是不抛出异常。
         *   ThreadPoolExecutor.DiscardOldestPolicy: 丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）
         *   ThreadPoolExecutor.CallerRunsPolicy: 重试添加当前的任务，自动重复调用 execute() 方法，直到成功
         */
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Bean(name = "otherPoolTaskExecutor")
    public ThreadPoolTaskExecutor executor2(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize(threadPoolConfig.getCoreNum());
        //线程最大数量，线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        taskExecutor.setMaxPoolSize(threadPoolConfig.getMaxNum());
        //缓存队列
        taskExecutor.setQueueCapacity(threadPoolConfig.getQueueSize());
        //超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setKeepAliveSeconds(threadPoolConfig.getQueueSize());
        //执行异步方法的线程名称
        taskExecutor.setThreadNamePrefix("otherAsyncTask");
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    /**
     * 指定默认线程池
     *
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        return executor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) ->
                log.error("线程池执行任务发生未知错误,执行方法:{}", method.getName(), ex);
    }

}
